package com.ruoyi.project.yf.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.yf.domain.YfStock;
import com.ruoyi.project.yf.domain.YfStockDayLine;
import com.ruoyi.project.yf.domain.YfStockNotice;
import com.ruoyi.project.yf.domain.vo.MyStockVo;
import com.ruoyi.project.yf.domain.vo.NoticeStockVo;
import com.ruoyi.project.yf.mapper.YfStockDayLineMapper;
import com.ruoyi.project.yf.service.IYfStockDayLineService;
import com.ruoyi.project.yf.service.IYfStockService;
import com.zjiecode.wxpusher.client.WxPusher;
import com.zjiecode.wxpusher.client.bean.Message;
import com.zjiecode.wxpusher.client.bean.MessageResult;
import com.zjiecode.wxpusher.client.bean.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.yf.mapper.YfStockMyMapper;
import com.ruoyi.project.yf.domain.YfStockMy;
import com.ruoyi.project.yf.service.IYfStockMyService;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 我的股票Service业务层处理
 * 
 * @author 云峰
 * @date 2020-06-15
 */
@Service
public class YfStockMyServiceImpl implements IYfStockMyService 
{

    @Autowired
    private RedisCache redisCache;


    @Autowired
    private IYfStockService stockService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private YfStockMyMapper yfStockMyMapper;

    @Autowired
    private YfStockDayLineMapper yfStockDayLineMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IYfStockDayLineService yfStockDayLineService;

    /**
     * 查询我的股票
     * 
     * @param id 我的股票ID
     * @return 我的股票
     */
    @Override
    public YfStockMy selectYfStockMyById(Long id)
    {
        return yfStockMyMapper.selectYfStockMyById(id);
    }

    /**
     * 查询我的股票列表
     * 
     * @param yfStockMy 我的股票
     * @return 我的股票
     */
    @Override
    public List<YfStockMy> selectYfStockMyList(YfStockMy yfStockMy)
    {
        return yfStockMyMapper.selectYfStockMyList(yfStockMy);
    }

    @Override
    public List<MyStockVo> selectMyStock(YfStockMy yfStockMy) {
        return yfStockMyMapper.selectMyStock(yfStockMy);
    }

    /**
     * 新增我的股票
     * 
     * @param yfStockMy 我的股票
     * @return 结果
     */
    @Override
    public int insertYfStockMy(YfStockMy yfStockMy)
    {
        YfStock qStock=new YfStock();
        qStock.setName(yfStockMy.getName());
        List<YfStock> stocks = stockService.selectYfStockList(qStock);
        if(stocks.size()>1){
            throw new CustomException(String.format("股票名称错误，请检查"));
        }else if(stocks.size()==0){
            //不存在，根据名称创建
            String code =  getStockCode(yfStockMy.getName());
            if(code.equals("")){
                throw new CustomException(String.format("股票名称错误，请检查"));
            }
            qStock.setCode(code);
            stockService.insertYfStock(qStock);
        }

        if(stocks.size()==1){
            qStock=stocks.get(0);
        }
        yfStockMy.setName(qStock.getName());
        yfStockMy.setStockId(qStock.getId());
        yfStockMy.setCreateTime(DateUtils.getNowDate());
        int id=yfStockMyMapper.insertYfStockMy(yfStockMy);
        if(qStock!=null){
            List<YfStock> stocksTemp=new ArrayList<>();
            stocksTemp.add(qStock);
            yfStockDayLineService.updatePriceByCodes(stocksTemp);
        }

        return id;
    }

    /**
     * 修改我的股票
     * 
     * @param yfStockMy 我的股票
     * @return 结果
     */
    @Override
    public int updateYfStockMy(YfStockMy yfStockMy)
    {
        yfStockMy.setUpdateTime(DateUtils.getNowDate());
        return yfStockMyMapper.updateYfStockMy(yfStockMy);
    }

    /**
     * 批量删除我的股票
     * 
     * @param ids 需要删除的我的股票ID
     * @return 结果
     */
    @Override
    public int deleteYfStockMyByIds(Long[] ids)
    {
        return yfStockMyMapper.deleteYfStockMyByIds(ids);
    }

    /**
     * 删除我的股票信息
     * 
     * @param id 我的股票ID
     * @return 结果
     */
    @Override
    public int deleteYfStockMyById(Long id)
    {
        return yfStockMyMapper.deleteYfStockMyById(id);
    }

    @Override
    public List<NoticeStockVo> selectNoiceStock() {
        return yfStockMyMapper.selectNoiceStock();
    }


    public  String getStockCode(String name){
        String code="";
        String result = restTemplate.getForObject("https://suggest3.sinajs.cn/suggest/key="+name+"&name=result",String.class);
        // 创建 Pattern 对象
        Pattern patt = Pattern.compile("var result=\"(.+)\";");
        Matcher matcher = patt.matcher(result);
        if(matcher.find()){
            for (String tempStock: matcher.group(1).split(";")) {
                String tempName=tempStock.split(",")[0];
                if(tempName.equals(name)){
                    code=tempStock.split(",")[3];
                    break;
                }
            }
        }
        return  code;
    }


    @Override
    public void SendNotice() {

        List<YfStockNotice> stockNotices = new ArrayList<>();
        List<NoticeStockVo> stockVoList =yfStockMyMapper.selectNoiceStock();
        for (NoticeStockVo item : stockVoList) {

            YfStockDayLine dayLine=yfStockDayLineMapper.selectYfStockDayLineById(item.getDaylineId());
            String text="【"+item.getName()+"】"+item.getSuggest()+"\n当前价格："+dayLine.getCurPrice()+"\t基准价格:"+item.getComparePrice()+"\t当前百分比："+dayLine.getPercent()+"\n操作建议："+dayLine.getRemark();


            YfStockNotice stockNotice = new YfStockNotice();
            stockNotice.setToUid(item.getCreateUid());
            stockNotice.setName(item.getName());
            stockNotice.setNoticeType(item.getSuggest());
            stockNotice.setRemark(text);
            //判断是否发送过消息，半小时发一次
            String key="stock:notice"+item.getCreateUid()+":"+stockNotice.getName()+":"+item.getSuggest();
            if(!redisCache.redisTemplate.hasKey(key)){ //不存在就发消息
                redisCache.setCacheObject(key,"1",15,TimeUnit.MINUTES);
                stockNotices.add(stockNotice);

                //获取用户推送key
                SysUser sysUser = sysUserMapper.selectUserById(item.getCreateUid());
                if(sysUser.getWxPushNumber().length()>0){
                    Message message = new Message();
                    message.setAppToken("AT_EAV2fkxOrsf1ndQcecOkQV9XcDoaHvI3");
                    message.setContentType(Message.CONTENT_TYPE_TEXT);
                    message.setContent(text);
                    message.setUid(sysUser.getWxPushNumber());
//                message.setUrl("https://xueqiu.com/S/SZ002038");//可选参数
                    Result<List<MessageResult>> result = WxPusher.send(message);
                }

            }


        }

    }


}
